import React, { useEffect, useRef } from "react";
import { useState } from "react";
import type * as CSS from 'csstype';
import { RailwayContext } from "./Railway";
import * as signalR from "@microsoft/signalr";
import type { ISubscription } from "@microsoft/signalr";
import { randomString } from "@/utils/tool";
import { ISRgvInfo } from "@/models/srgv";

export interface IVehicleProps {

  /**
   * 车辆名称
   */
  rgvName: string;

  /**
  * 车体绘制颜色
  */
  color?: CSS.Property.BackgroundColor;

  /**
   * 多少毫秒接收一次数据
   */
  ms: number;

  /**
   * 数据源的 url 地址
   */
  url: string;

}


export const Vehicle: React.FC<IVehicleProps> = (props) => {
  const [position, setPosition] = useState<number>();
  const subRef = useRef<ISubscription<any>>();
  const connRef= useRef<signalR.HubConnection>();


  useEffect(() => {

    const connect = async () => {
      const connection = new signalR.HubConnectionBuilder().withUrl(props.url, {
        withCredentials: false,
      }).build();
      connRef.current = connection;
      try {
        await connection.start();

        subRef.current = connection.stream<ISRgvInfo>("SRgv", props.rgvName, props.ms)
          .subscribe({
            next: (item) => {
              console.log(props.ms, item.state?.position);
              setPosition(item.state?.position);
            },
            complete: () => {
            },
            error: (err) => {
              // eslint-disable-next-line no-console
              console.log(err);
            },
          });

      } catch (err) {
        // eslint-disable-next-line no-console
        console.log(err);
      }
    };

    connect();

    return () => {
      if (subRef.current) {
        subRef.current.dispose();
        subRef.current = undefined;
      }
      if (connRef.current && connRef.current.state === 'Connected') {
        connRef.current.stop();
      }
    };

  }, []);

  return (
    <RailwayContext.Consumer>
      {({ computeLeft, computeTop }) => (
        <div
          style={{
            width: 56,
            height: '100%',
            position: 'absolute',
            transition: position ? `left ${props.ms}ms linear, top ${props.ms}ms linear` : '',
            left: computeLeft(position ?? 0),
            top: computeTop(position ?? 0),
            display: position ? 'block' : 'none',
            backgroundColor: props.color,
            borderRadius: 4
          }}>

        </div>
      )}
    </RailwayContext.Consumer>

  );
};
